package com.igeek.health.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.aliyuncs.exceptions.ClientException;
import com.igeek.health.constant.MessageConstant;
import com.igeek.health.constant.RedisMessageConstant;
import com.igeek.health.entity.Order;
import com.igeek.health.result.Result;
import com.igeek.health.service.IOrdersService;
import com.igeek.health.utils.SMSUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * @Author fengqq
 * @Description TODO
 * @Date 2024/9/11  14:42
 */
@RestController
@RequestMapping("/app/order")
@Api(tags = "预约订单模块的控制层")
@CrossOrigin //处理跨越问题
@Slf4j
public class OrderController {
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/submit")
    public Result submit(@RequestBody  Map<String,Object> map) throws ClientException {
        //1.校验手机号验证码是否正确  1888888_001_1234
        String telephone = map.get("telephone").toString();
        String validateCode = map.get("validateCode").toString();
        log.info("validateCode:{}",validateCode);
        String validateCodeInRedis =
                stringRedisTemplate.opsForValue().get(telephone + "_" + RedisMessageConstant.SENDTYPE_ORDER +"_"+ validateCode);
        log.info("validateCodeInRedis:{}",validateCodeInRedis);
        if(!StringUtils.hasLength(telephone) || !StringUtils.hasLength(validateCode)){
            return new Result(false, MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);
        }
        if(!StringUtils.hasLength(validateCodeInRedis) || !validateCode.equals(validateCodeInRedis)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        //2.填充 预约类型 和 预约状态
        map.put("orderType", Order.ORDERTYPE_WEIXIN);
        map.put("orderStatus", Order.ORDERSTATUS_NO);

        //3.提交预约的业务操作
        Result result = ordersService.submit(map);
        //4.成功预约后 发送短信通知
        if(result.isFlag()){
            //预约日期 2024-09-11 --> 24-09-11 --》 240911
            //字符串 转换为 date对象 2024-09-11
            Date orderDate = DateUtil.parse(map.get("orderDate") + "", "yyyy-MM-dd");
            //date对象 转换为 字符串 240911
            String code = DateUtil.format(orderDate, "yyMMdd");
            log.info("code:{}",code);
            SMSUtils.sendMessage(SMSUtils.ORDER_NOTICE_CODE,telephone,code);
        }
        return result;
    }
}
